# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets

from controller.hypervisor_manager import HypervisorManager
from controller.window_qt5_ui import *

_translate = QtCore.QCoreApplication.translate


class myQWebView(QtWebKitWidgets.QWebView):
    def mousePressEvent(self, event):
        super(myQWebView, self).mousePressEvent(event)
        print("myQWebView, mousePressEvent ", event)

    def mouseReleaseEvent(self, event):
        super(myQWebView, self).mouseReleaseEvent(event)
        print("myQWebView, mouseReleaseEvent ", event)

    def mouseDoubleClickEvent(self, event):
        super(myQWebView, self).mouseDoubleClickEvent(event)
        print("myQWebView, mouseDoubleClickEvent ", event)

    def mouseMoveEvent(self, event):
        super(myQWebView, self).mouseMoveEvent(event)
        #print("myQWebView, mouseMoveEvent ", event)



class MainWindow(QMainWindow, Ui_MainWindow):
    hpmng = HypervisorManager()
    vmname = ''

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.tableWidget_RowCount = len(MainWindow.hpmng.list())
        print('%d' % self.tableWidget_RowCount)
        self.setupUi(self)
        self.customContextMenuRequested()

    def customContextMenuRequested(self):
        self.label_5.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_6.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_7.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_11.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_12.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_13.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_20.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_21.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_22.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_26.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_27.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_28.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_32.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_33.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_34.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_38.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_39.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)
        self.label_40.customContextMenuRequested[QtCore.QPoint].connect(self.myListWidgetContext)

    def retranslateUi(self, mainWindow):
        # 添加图标
        super(MainWindow, self).retranslateUi(mainWindow)
        self.label_5.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_6.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_7.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_11.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_12.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_13.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_28.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_26.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_27.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_20.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_21.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_22.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_32.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_33.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_34.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_38.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_39.setPixmap(QtGui.QPixmap('logos/test.png'))
        self.label_40.setPixmap(QtGui.QPixmap('logos/test.png'))

        # 设置对应图标下的虚拟机名称（并设置对应图标的setWindowIconText，供后面使用）
        self.label_8.setText(_translate("mainWindow", MainWindow.hpmng.list()[0].vm_name))
        self.label_5.setWindowIconText(MainWindow.hpmng.list()[0].vm_name)
        self.label_9.setText(_translate("mainWindow", MainWindow.hpmng.list()[1].vm_name))
        self.label_6.setWindowIconText(MainWindow.hpmng.list()[1].vm_name)
        self.label_10.setText(_translate("mainWindow", MainWindow.hpmng.list()[2].vm_name))
        self.label_7.setWindowIconText(MainWindow.hpmng.list()[2].vm_name)
        self.label_14.setText(_translate("mainWindow", MainWindow.hpmng.list()[3].vm_name))
        self.label_11.setWindowIconText(MainWindow.hpmng.list()[3].vm_name)

        i = 0
        while i < self.tableWidget_RowCount:
            item = self.tableWidget.item(i, 0)
            item.setText(_translate("mainWindow", MainWindow.hpmng.list()[i].vm_name))
            item = self.tableWidget.item(i, 1)
            item.setText(_translate("mainWindow", MainWindow.hpmng.list()[i].vm_status))
            i = i + 1
            # 向tabWidget添加tab页

    # cpu实时曲线
    def update_line_cpu(self, i):
        # 获取cpu利用率
        cpuAll = os.popen('top -bi -n 2 -d 0.02 |grep Cpu | cut -d "," -f 4 | cut -d ":" -f 5').read().split('\n')[1]  # 原始形式 1.9 us
        cpuIdleString = cpuAll.strip().split(' ')[0]  # 处理后的形式 1.9
        cpuIdleRate = float(float(cpuIdleString)/100)
        #print('cpuIdleRate = %f' % cpuIdleRate)
        self.user_cpu = self.user_cpu[1:] + [1 - cpuIdleRate]
        self.l_user_cpu.set_ydata(self.user_cpu)
        return self.l_user_cpu,

    def myListWidgetContext(self, point):
        popMenu = QtWidgets.QMenu()
        sender = self.sender()
        self.vmname = sender.windowIconText()
        print('右键单击 %s ' % self.vmname)
        popMenu.addAction(QtWidgets.QAction('启动', self, triggered=self.startItem))
        popMenu.addAction(QtWidgets.QAction('关闭', self, triggered=self.shutdownItem))
        popMenu.addAction(QtWidgets.QAction('暂停', self, triggered=self.pauseItem))
        popMenu.addAction(QtWidgets.QAction('恢复', self, triggered=self.resumeItem))
        popMenu.exec_(QtGui.QCursor.pos())

    def startItem(self):
        print('startItem %s'%  self.vmname)
        MainWindow.hpmng.start(self.vmname)
        self.update_vm_status(self.vmname)

    def shutdownItem(self):
        print('shutdownItem %s'%  self.vmname)
        MainWindow.hpmng.shutdown(self.vmname)
        self.update_vm_status(self.vmname)

    def pauseItem(self):
        print('pauseItem %s'%  self.vmname)
        MainWindow.hpmng.pause(self.vmname)
        self.update_vm_status(self.vmname)

    def resumeItem(self):
        print('resumeItem %s' %  self.vmname)
        MainWindow.hpmng.resume(self.vmname)
        self.update_vm_status(self.vmname)

    def update_vm_status(self, vmname):
        print('更新虚拟机状态')
        i = 0
        index = 0
        while i < self.tableWidget_RowCount:
            item = self.tableWidget.item(i, 0)
            if item.text() == vmname:
                index = i
                break
            i = i + 1

        for vm in MainWindow.hpmng.list():
            if vm.vm_name == vmname:
                item = self.tableWidget.item(index, 1)
                item.setText(_translate("mainWindow", vm.vm_status))

    def add_label(self, windowIconText):
        sender = self.sender()
        self.vmname = sender.windowIconText()
        print('左键单击 %s'% self.vmname)
        if windowIconText not in self.label_list:
            self.label_list.append(windowIconText)
            self.newLabel = QtWidgets.QWidget()
            self.newLabel.setObjectName(windowIconText)
            self.tabWidget.addTab(self.newLabel, "")
            self.tabWidget.setTabText(self.tabWidget.indexOf(self.newLabel),
                                      _translate("mainWindow", windowIconText))
            self.tabWidget.setCurrentIndex(self.label_list.index(windowIconText))
        else:
            self.tabWidget.setCurrentIndex(self.label_list.index(windowIconText))

        for vm in MainWindow.hpmng.list():
            if vm.vm_name == self.vmname:
                if vm.vm_status == '关机':
                    self.show_shutdown_tab_page()
                else:
                    self.show_started_tab_page()

    # todo
    def show_shutdown_tab_page(self):
        print('显示关机状态的tab页')

    # todo
    def show_started_tab_page(self):
        print('显示开机状态的tab页')
        self.verticalLayout_8 = QtWidgets.QVBoxLayout(self.newLabel)
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        self.webView = myQWebView(self.newLabel)
        url = 'http://127.0.0.1:6081/vnc_auto.html'
        self.webView.setUrl(QtCore.QUrl(url))
        self.webView.setObjectName("webView")
        self.verticalLayout_8.addWidget(self.webView)



if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwin = MainWindow()
    mainwin.show()
    app.exec_()

